package com.wxy.ideaplugin.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sun.istack.Nullable;
import com.wxy.ideaplugin.ui.AiCodeUi;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import okhttp3.sse.EventSource;
import okhttp3.sse.EventSourceListener;
import okhttp3.sse.EventSources;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.swing.*;

//@Slf4j
public class HttpUtils {
    private static final Logger log = LoggerFactory.getLogger(HttpUtils.class);

    private String client_secret;
    //private String accessToken = "24.483c1d360dd554a6b790d3df7e76d72d.2592000.1720604981.282335-39692580";
    private String accessToken;
    // price: https://cloud.baidu.com/doc/WENXINWORKSHOP/s/hlrk4akp7
    // private String ERNIE_4d0_8K = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions_pro?access_token=";
    // private String ERNIE_Speed_128K = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/ernie-speed-128k?access_token=";
    // private String ERNIE_3d5_8K = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/ernie-3.5-8k-0205?access_token=";
    private String api_url;

    private Map<String,String> resourceMap;


    private HttpUtils() {
    }

    private static HttpUtils httpUtils = new HttpUtils();

    public static HttpUtils getInstance() {
        log.info("getInstance");
        if (httpUtils.client_secret==null || httpUtils.accessToken==null || httpUtils.api_url==null) {
            log.info("getInstance is null");
            httpUtils.resourceMap = AiResourceUtils.parseAiCodeResourceFile(AiCodeUi.projectPath);
            httpUtils.client_secret = httpUtils.resourceMap.get("client_secret");
            httpUtils.api_url = httpUtils.resourceMap.get("api_url")+"?access_token=";
            httpUtils.accessToken = httpUtils.queryToken();
        }
        log.info(httpUtils.client_secret);
        log.info(httpUtils.api_url);
        log.info(httpUtils.accessToken);
        return httpUtils;
    }


    public static void main(String[] args) {
        //String accessToken = new HttpUtils("/Users/wxy2020/workspace/gitee/lowcode2/").queryToken();
        //System.out.println(accessToken);
        //String msg = "你是一位数据库设计师，设计一款软件系统，系统名称叫电子商务系统，请编写出系统的数据库表名的JSON结构，对数据库表名进行分类分组，JSON结构格式是，json键：功能组名称，json值：表名列表结构，表名结尾去掉'表'字；json脚本内容，不要省略，需要显示全部数据；json结构中只显示功能组名称和数据表名称，不要显示系统名称；组名和表名使用中文描述。";
        //chat4GroupMenu(msg, null);
    }

    public static OkHttpClient createOkHttpClient() {
        return new OkHttpClient.Builder()
                .connectTimeout(100, TimeUnit.SECONDS) // 连接超时时间
                .readTimeout(100, TimeUnit.SECONDS)    // 读取超时时间
                .writeTimeout(100, TimeUnit.SECONDS)   // 写入超时时间
                .build();
    }

    public String queryToken() {
        try {
            OkHttpClient okHttpClient = createOkHttpClient();
            String url_token = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=RzrVj9S1dQ8WUVXMb17gmolQ&client_secret="+client_secret;
            Request request = new Request.Builder().url(url_token).method("GET",null).build();
            Call call = okHttpClient.newCall(request);
            Response response = call.execute();
            String data = response.body().string();
            JSONObject jsonObject = JSONObject.parseObject(data);
            String accessToken = jsonObject.getString("access_token");
            return accessToken;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public void chatApiV2(String q, EventSourceListener eventSourceListener) {
        String url = api_url+accessToken;

        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(50, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.MINUTES)
                .build();

        EventSource.Factory factory = EventSources.createFactory(client);
        // 请求体
        JSONObject contentJson = new JSONObject();
        contentJson.put("role", "user");
        contentJson.put("content", q);
        JSONArray contentArr = new JSONArray();
        contentArr.add(contentJson);
        JSONObject json = new JSONObject();
        json.put("messages", contentArr);
        json.put("stream", true);
        //log.info("----chatApiV2 param");
        //log.info(json.toJSONString());

        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"),json.toJSONString());
        // 请求对象
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();

        // 创建事件
        EventSource eventSource = factory.newEventSource(request, eventSourceListener);
    }

    public static String parseGroupMenuList(String msg) {
        if (msg.contains("```json")){
            msg = msg.substring(msg.indexOf("```json"));
            msg = msg.replaceAll("```json", "");
        }
        if (msg.contains("```")) {
            msg = msg.substring(0, msg.indexOf("```"));
        }
        msg.replaceAll("\n\n", "\n");
        return msg;
    }

    /*public String chatApiSync(String q) {
        try {
            JSONObject contentJson = new JSONObject();
            contentJson.put("role", "user");
            contentJson.put("content", q);
            JSONArray contentArr = new JSONArray();
            contentArr.add(contentJson);
            JSONObject msgJson = new JSONObject();
            msgJson.put("messages", contentArr);

            RequestBody body = RequestBody.create(MediaType.parse("application/json"), msgJson.toJSONString());
            OkHttpClient okHttpClient = createOkHttpClient();
            String url = ERNIE_3d5_8K+accessToken;
            Request request = new Request.Builder().url(url).post(body).build();
            Call call = okHttpClient.newCall(request);
            Response response = call.execute();
            String data = response.body().string();
            JSONObject jsonObject = JSONObject.parseObject(data);
            String result = jsonObject.getString("result");
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }*/

    /*public void chatApiAsync(String q, Callback callback) {
        try {
            JSONObject contentJson = new JSONObject();
            contentJson.put("role", "user");
            contentJson.put("content", q);
            JSONArray contentArr = new JSONArray();
            contentArr.add(contentJson);
            JSONObject msgJson = new JSONObject();
            msgJson.put("messages", contentArr);

            RequestBody body = RequestBody.create(MediaType.parse("application/json"), msgJson.toJSONString());
            OkHttpClient okHttpClient = createOkHttpClient();
            String url = ERNIE_3d5_8K+accessToken;
            Request request = new Request.Builder().url(url).post(body).build();
            Call call = okHttpClient.newCall(request);
            call.enqueue(callback);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }*/


}
